package com.cari.oa.manage;

import com.cari.oa.controller.LoginController;
import com.cari.oa.util.StrUtils;

import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;

/**
 * 权限控制的拦截器
 * User: yexuhui
 * Date: 12-12-13
 * Time: 上午11:33
 */
public class BaseInterceptor implements HandlerInterceptor {

    private static Set<String> publicUrlSet;
    private static Set<String> systemUrlSet;

    @SuppressWarnings("unchecked")
	@Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object o) throws Exception {
        //初始化UrlSet
        if(publicUrlSet == null) {
        	publicUrlSet = new HashSet<String>();
            String urlsStr = request.getSession().getServletContext().getInitParameter("publicUrl");
            if(!StrUtils.isEmpty(urlsStr)) {
            	publicUrlSet.addAll(Arrays.asList(urlsStr.split(",")));
            }
            
            systemUrlSet = new HashSet<String>();
            urlsStr = request.getSession().getServletContext().getInitParameter("systemUrl");
            if(!StrUtils.isEmpty(urlsStr)) {
            	systemUrlSet.addAll(Arrays.asList(urlsStr.split(",")));
            }
        }

        //public URL，允许直接访问
        String url = request.getServletPath();
        if(publicUrlSet.contains(url)) return true;
        //session不存在，访问其它URL，会被转移到login.do
        if(request.getSession().getAttribute(LoginController.USER_NAME_ATTR) == null) {
            response.sendRedirect(request.getContextPath() + "/login.do");
            return false;
        }
        //session存在，访问system URL，允许访问
        if(systemUrlSet.contains(url)) return true;
        //session存在，访问其它URL，需要判断action set中是否存在
        Set<String> actionSet = (Set<String>)request.getSession().getAttribute(LoginController.ACTION_URL_SET_ATTR);
        if (!actionSet.contains(url)) throw new Exception("您无权访问该地址，url:" + url);
        
        return true;
    }

    @Override
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object o, ModelAndView modelAndView) throws Exception {

    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object o, Exception e) throws Exception {

    }
}
